const fs = require('fs');
const path = require('path');
const puppeteer = require('puppeteer');
const marked = require('marked');
const replaceExt = require('replace-ext');


const generateImage = async (input, width) => {
  const output = path.resolve(replaceExt(input, '.png'));
  const document = fs.readFileSync(input, 'utf8');
  const content = marked(document)
  const html = `<link rel="stylesheet" href="https://unpkg.com/github-markdown-css">
    <div class="markdown-body" style="padding: 2.5em">${content}</div>`;
  return openWindow(html, width, output);
}

const openWindow = async (content, width, output) => {
  // 创建无头浏览器、截图、关闭
  
  const browser = await puppeteer.launch()
  const page = await browser.newPage()
  await page.setViewport({
    width,
    height: 100
  })
  await page.setContent(content)
  await page.screenshot({
    path: output,
    fullPage: true
  })
  await browser.close()
  return output
}


const main = async (input, width = 800) => {
  if (typeof input !== 'string') {
    throw new TypeError(`Expected a string, got ${typeof input}: ${input}`)
  }

  input = path.resolve(input)

  width = parseInt(width)

  if (!fs.existsSync(input)) {
    throw new Error('The specified input path does not exist')
  }
  if (!fs.statSync(input).isFile()) {
    throw new Error('The specified input path is a directory');
  }

  return generateImage(input, width);
}

module.exports = main;

 // = main;